#-*-coding:utf-8-*-

'''
# ----------------------------------------------------------------------------
#  Purpose:     用于实现文件压缩以及解压缩功能

#  Author:      青衫少年春归也

#  Created:     2019.12.23

# ----------------------------------------------------------------------------
'''
import os
import zipfile
import rarfile


class HandleFileCompress():
    def compress_folder_to_zip(self, dirname, zipfilename):
        '''
        打包文件夹(包括顶层文件夹也打包进去)
        参数信息：
            :param dirname: 文件夹目录
            :param zipfilename: 压缩包文件目录
        返回值:
            文件打包处理结果
        '''
        filelist = []
        if os.path.isfile(dirname):
            filelist.append(dirname)
        else:
            for root, dirs, files in os.walk(dirname):
                for name in files:
                    filelist.append(os.path.join(root, name))
        zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
        for tar in filelist:
            try:
                arcname = tar[len(os.path.dirname(dirname)):]
                zf.write(tar, arcname)
            except Exception as e:
                print(f"打包文件失败，原因：{str(e)}")
                return False
        zf.close()
        return True


    def extract_file(self, file_path:str, target_path:str):
        '''
        解压 rar或者zip 压缩包
        参数信息：
            :param file_path: 压缩文件地址
            :param target_path: 解压目标目录地址
        '''
        try:
            ext = os.path.splitext(file_path)[1]
        except Exception as e:
            raise(u"获取文件后缀名失败, 路径%s" % file_path)
        if not os.path.isdir(target_path):
            os.mkdir(target_path)
        if ext == '.rar':
            self._rar_extractall(file_path, target_path)
        elif ext == '.zip':
            self._zip_extractall(file_path, target_path)
        else:
            raise(u"不支持的文件格式: %s" % ext)


    def _rar_extractall(self, rar_file_path, dst_dir):
        '''
        解压 rar 压缩包
        参数信息：
            :param rar_file_path: rar压缩文件地址
            :param dst_dir: 解压目标目录地址
        '''
        rar_file = rarfile.RarFile(rar_file_path)
        rar_file.extractall(dst_dir)


    def _zip_extractall(self, zip_file_path:str, dst_dir:str):
        '''
        解压 zip 压缩包
        参数信息：
            :param zip_file_path: zip压缩文件地址
            :param dst_dir: 解压目标目录地址
        '''
        zip_ins = zipfile.ZipFile(zip_file_path, 'r')
        zip_ins.extractall(dst_dir)
        zip_ins.close()
